package com.mid;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lxk on 2019/7/7.
 */
public class Solution129 {

    private List<Integer> numsList = new ArrayList<>();

    private void preVisit(TreeNode cur, int[] nums, int pos) {
        if (cur == null) {
            return;
        }
        nums[pos] = cur.val;
        if (cur.left == null && cur.right == null) {
            int num = 0;
            for (int i = 0; i <= pos; i++) {
                num = num * 10 + nums[i];
            }
            numsList.add(num);
            return;
        }
        preVisit(cur.left, nums, pos + 1);
        preVisit(cur.right, nums, pos + 1);
    }

    public int sumNumbers(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int[] nums = new int[27];
        preVisit(root, nums, 0);
        int sum = 0;
        for (int val : numsList) {
            sum += val;
        }
        return sum;
    }

    public static void main(String[] args) {
        TreeNode node = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node5 = new TreeNode(3);
        node.left = node2;
        node.right = node5;
        Solution129 solution129 = new Solution129();
        System.out.println(solution129.sumNumbers(node));
    }

}
